<?php
declare (strict_types=1);

namespace app\circle\model\admin;

use app\common\logic\Attach as AttachLogic;
use app\common\model\BaseModel;
use app\user\model\user\Account as User;
use think\model\concern\SoftDelete;

/**
 * Class Comment
 *
 * @package app\circle\model\admin
 */
class Comment extends BaseModel
{
    use softDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'circle_comment';

    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    /**
     * 关联用户头像和昵称
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-21
     *
     * @return [type] [description]
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')->with(['avatar_url'])->bind(['nick_name', 'avatar_url']);
    }

    /**
     * 关联回复用户昵称
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-21
     *
     * @return [type] [description]
     */
    public function replyUserName()
    {
        return $this->belongsTo(User::class, 'reply_user_id')->bind(['reply_user_name' => 'nick_name']);
    }

    /**
     * 附件url获取器
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param string $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function getAttachUrlAttr($value = '', $data)
    {
        $url = [];
        if (!isset($data['attach']) || !$data['attach']) return $url;
        $attach = json_decode($data['attach'], true);
        if (!count($attach)) return $url;
        if (is_array($attach)) {
            foreach ($attach as $id) {
                $attach = AttachLogic::find($id);
                if ($attach) {
                    if (app(AttachLogic::class)->isAudioOrVideo($attach)) {
                        $urls  = array_column($attach->fileurl, null, 'definition');
                        $url[] = $urls['OD']['play_url'];
                    } else {
                        $url[] = $attach->fileurl ?? '';
                    }
                } else {
                    $url[] = '';
                }
            }
        }

        return $url;
    }
}